package com.qf.commons.sentinel.config.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import com.qf.data.base.r.Codes;
import com.qf.data.base.r.R;
import com.qf.data.base.r.Rs;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 普通微服务的Sentinel异常处理
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
public class ServiceSentinelExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException t) throws Exception {
        R rs = null;

        if (t instanceof FlowException) {
            //限流异常
            rs = Rs.createFail(Codes.REQUEST_TO_MANY);
        } else if (t instanceof DegradeException) {
            //降级异常
            rs = Rs.createFail(Codes.SERVICE_DEGRADE);
        }

        //通过response响应数据
        response.setStatus(Codes.FAIL.getCode());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println(JSON.toJSONString(rs));
        writer.close();
    }
}
